#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Common.hpp"
#include "Log.hpp"

using namespace My_Log;

const in_port_t defport = 8080;
const std::string defip = "127.0.0.1";

class UdpServer
{
public:
    UdpServer(in_port_t port = defport, std::string ip = defip)
        : _sokfd(-1), _port(port), _ip(ip), _isrunning(false)
    {
    }
    void InitServer()
    {
        _sokfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sokfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket err: " << strerror(errno);
            exit(SOCKET_ERR);
        }

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());

        int n = bind(_sokfd, CONV(&local), sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            exit(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }
    void Start()
    {
        _isrunning = true;

        while (true)
        {
            char recbuff[1024] = {0};
            struct sockaddr_in cliaddr;
            socklen_t len = sizeof(cliaddr);
            int n = recvfrom(_sokfd, recbuff, 1024, 0, CONV(&cliaddr), &len);
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "recvfrom err" << strerror(errno);
                exit(REC_ERR);
            }

            std::string message = recbuff;
            LOG(LogLevel::DEBUG) << "Server receive message# " << message;

            sendto(_sokfd, recbuff, n, 0, CONV(&cliaddr), len);
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
        if(_sokfd > -1)
            close(_sokfd);
    }

private:
    int _sokfd;
    in_port_t _port;
    std::string _ip;

    bool _isrunning;
};